package com.iot.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot.manage.pojo.App;
import com.iot.manage.pojo.Area;
import com.iot.manage.result.Code;
import com.iot.manage.result.Result;
import com.iot.manage.service.AppService;
import com.iot.manage.service.TokenService;
import com.iot.manage.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 应用管理控制层
 *
 * @author zhuzhi
 */
@RestController
@RequestMapping("/api/private/v1")
public class AppController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AppService appService;

    /**
     * 查询应用信息列表
     *
     * @param token
     * @param query 模糊查询关键字
     * @param pagenum 当前页
     * @param pagesize 每页条数
     * @return
     */
    @GetMapping("/findAppList")
    public Result findAppList(
            @RequestHeader("token") String token,
            @RequestParam("query") String query,
            @RequestParam("pagenum") int pagenum,
            @RequestParam("pagesize") int pagesize) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<App> appList;
        int appTotal;
        try {
            appList = appService.findAppsInfo(query,pagenum,pagesize);
            appTotal = appService.countAppsInfo(query);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total",appTotal);
        map.put("pagenum",pagenum);
        map.put("appList",appList);
        return result.build(map, Code.S200);
    }

    /**
     *删除应用信息
     *
     * @param token
     * @param appId 应用ID
     * @return
     */
    @DeleteMapping("/deleteAppById/{appId}")
    public Result deleteAppById(
            @RequestHeader("token") String token,
            @PathVariable("appId") String appId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            appService.deleteAppById(appId);
            appService.deleteRelevancyUserById(appId);
            appService.deleteRelevancyAreaById(appId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 新增应用信息
     *
     * @param token
     * @param params 应用信息参数
     * @return
     */
    @PostMapping("/addApp")
    public Result addApp(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if(null != findAppByIdOrCode(token,params.getString("appCode")).getData()){
                return result.build(null, Code.D411);
            }
            params.put("appId", UUID.randomUUID().toString().replace("-", ""));
            params.put("appArg",StringUtils.replaceBlank(params.get("appArg").toString()));
            appService.addApp(params);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 根据应用ID或应用标识查询应用信息
     *
     * @param token
     * @param params 应用ID或应用标识
     * @return
     */
    @GetMapping("/findAppById/{params}")
    public Result findAppByIdOrCode(
            @RequestHeader("token") String token,
            @PathVariable("params") String params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        App app;
        try{
            app = appService.findAppByIdOrCode(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(app, Code.S200);
    }

    /**
     * 修改应用应用信息
     *
     * @param token
     * @param params 应用信息参数
     * @return
     */
    @PutMapping("/updateAppInfo/{oldAppCode}")
    public Result updateAppInfo(
            @RequestHeader("token") String token,
            @PathVariable("oldAppCode") String oldAppCode,
            @RequestBody JSONObject params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if (!(oldAppCode.equals(params.get("appCode")))){
                if(null != findAppByIdOrCode(token,params.getString("appCode")).getData()){
                    return result.build(null, Code.D411);
                }
            }
            params.put("appArg",StringUtils.replaceBlank(params.get("appArg").toString()));
            appService.updateAppInfo(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 查询全部区域
     *
     * @param token
     * @return
     */
    @GetMapping("/findAllAllotArea")
    public Result findAllAllotArea(
            @RequestHeader("token") String token) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Area> areasList;
        try {
            areasList = appService.findAllAllotArea();
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(areasList, Code.S200);
    }

    /**
     * 根据应用ID查询已分配的区域
     *
     * @param token
     * @param appId 应用ID
     * @return
     */
    @GetMapping("/findAllotAreaById/{appId}")
    public Result findAllotAreaById(
            @RequestHeader("token") String token,
            @PathVariable("appId") String appId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<String> areaIdsList;
        try {
            areaIdsList = appService.findAllotAreaById(appId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(areaIdsList, Code.S200);
    }

    /**
     * 保存分配的区域
     *
     * @param token
     * @param params 分配的区域信息
     * @return
     */
    @PostMapping("/saveAreaToApp")
    public Result saveAreaToApp(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Map<String,String>> list = new ArrayList<>();
        try{
            //删除该应用已分配的区域
            appService.deleteAreasOfAllotById(params.getString("appId"));
            String appIdsStr = params.getString("areaIds").substring(1, params.getString("areaIds").length() - 1);
            if (!("".equals(appIdsStr))){
                String[] areaIdsArr = appIdsStr.replaceAll(" ","").split(",");
                for (int i = 0; i < areaIdsArr.length; i++) {
                    Map<String,String> map = new HashMap<>();
                    map.put("appId",params.getString("appId"));
                    map.put("areaId",areaIdsArr[i]);
                    list.add(map);
                }
                appService.addAreasOfAllotById(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S210);
    }
}
